package com.apexedu.portal.controller;

import com.apexedu.framework.util.ConfigUtil;
import com.apexedu.framework.util.DBUtil;
import com.apexedu.framework.util.Pager;
import com.apexedu.identity.IdConstants;
import com.apexedu.identity.entity.TSysMenu;
import com.apexedu.identity.entity.TSysUser;
import com.apexedu.portal.constant.Constants;
import com.apexedu.portal.entity.Lbxx;
import com.apexedu.portal.entity.TLbxx;
import com.apexedu.portal.entity.TMessage;
import com.apexedu.portal.util.DBMUtil;
import com.apexedu.portal.util.LittleTimer;
import com.apexedu.util.StringUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 所有控制类的父类
 * Created by ly on 2014/8/8.
 */
public class BaseController {
    protected Log log = LogFactory.getLog(this.getClass());//日志记录

    public void error(Throwable e, String str, Object... parms) {
        log.error(format(str, parms), e);
    }

    public void error(String str, Object... parms) {
        log.error(format(str, parms));
    }

    public void debug(String str, Object... parms) {
        log.debug(format(str, parms));
    }

    public void warn(String str, Object... parms) {
        log.warn(format(str, parms));
    }

    public void info(String str, Object... parms) {
        log.info(format(str, parms));
    }

    /**
     * 格式化日志字符串
     *
     * @param str   日志字符串
     * @param parms 参数
     * @return
     */
    private String format(String str, Object... parms) {
        int i = 0;
        while (str.indexOf("{}") != -1 && parms.length > i) {
            str = str.replaceFirst("\\{\\}", java.util.regex.Matcher.quoteReplacement(String.valueOf(parms[i])));
            i++;
        }
        return str;
    }

    /**
     * 获取用户类型
     *
     * @param request
     */
    protected String getUsertype(HttpServletRequest request) {
        debug("<<{}>> getUsertype start", this.getClass().getSimpleName());
        LittleTimer timer = new LittleTimer();
        try {
            TSysUser user = (TSysUser) request.getSession().getAttribute(IdConstants.SESSION_USER);
            String type = (String) request.getSession().getAttribute("type");//用户类型 参考Constants.MhShghUserType

            if ("admin".equals(user.getUserloginid())) {
                type = request.getParameter("type");
                if (StringUtil.isBlank(type)) {
                    type = (String) request.getSession().getAttribute("type");
                    if (StringUtil.isBlank(type)) {
                        type = Constants.MhUserType.LS;
                    }
                }
            } else if (StringUtil.isBlank(type)) {
                type = (String) DBUtil.queryFieldValue("select case when groupid=1 then 'ls' when groupid=2 then 'xs' when groupid=3 then 'ld' end" +
                                " from t_yhzd a inner join t_sys_user b on a.yhlx=b.usertype where userloginid=?",
                        user.getUserloginid());
            }
            request.getSession().setAttribute("type", type);
            request.setAttribute("type", type);
            return type;
        } catch (Exception e) {
            error("<<{}>> getUsertype error : {}", this.getClass().getSimpleName(), e);
            throw new RuntimeException(e);
        } finally {
            debug("<<{}>> getUsertype end : {}", this.getClass().getSimpleName(), timer.end());
        }
    }

    /**
     * 获取订阅服务集合
     *
     * @param userloginid 用户登录账号
     * @param fwid        服务组件id(默认服务、订阅服务等)
     * @return
     */
    public List<TSysMenu> getDyfwList(String userloginid, String fwid) {
    	/*查询出指定用户的指定服务类别(目测：1是固定服务，2是自己订阅的服务)下所有服务的id*/
//        String sql = "select to_char(nvl(wmsys.wm_concat(dy.menuid),' ')) from t_fw_dy dy " //oracle11g 不支持 wmsys.wm_concat函数
//        		+ "inner join t_fw fw on fw.wid=dy.fwid"
//        		+" where fw.portletid=? and (fw.fwlb!='2' or dy.userid=?)";
        String sql = "select listagg(dy.menuid, ',') within group(order by dy.menuid) from t_fw_dy  dy "
        		+ "inner join t_fw fw on fw.wid=dy.fwid"
        		+" where fw.portletid=? and (fw.fwlb!='2' or dy.userid=?)";
        String mrfwids = DBUtil.queryField(sql, fwid, userloginid);
        
        /*查询出服务列表*/
        sql = "select menuid,menuname,sftj,replace(menupath,'{userid}','" + userloginid + "') as menupath,upmenuid,tb,djcs,color,bgcolor "
                + " from t_sys_menu a "
                + " where 1=1 "
                + " and a.state = 1 and a.belongtoapp=?"
                + " and exists (select null from t_sys_user u,t_sys_user_role b,t_sys_role c,t_sys_role_menu d"
                + " where u.userid=b.userid and b.roleid=c.roleid and  c.roleid=d.roleid and d.menuid=a.menuid  and c.state=1 and u.userloginid=?)"
                + " and length(menuid)>9 and menuid in ('" + mrfwids.replaceAll(",", "','") + "') order by upmenuid,ordernum desc,menuid";
        List<TSysMenu> listMenuSub = DBUtil.queryAllBeanList(sql, TSysMenu.class, ConfigUtil.getString("portalCode"), userloginid);
        return listMenuSub;
    }

    /**
     * 获取服务资源分类集合
     *
     * @return 服务资源分类集合
     */
    protected List<TSysMenu> getDyfwTypeList() {
        String sql = "select menuid,menuname from t_sys_menu a where a.belongtoapp=? and length(menuid)=9 order by ordernum desc";
        return DBUtil.queryAllBeanList(sql, TSysMenu.class, ConfigUtil.getString("portalCode"));
    }

    /**
     * 获取通知公告集合
     *
     * @param dbmUtil 数据源
     * @param id
     * @param sql
     * @return
     * @throws Exception
     */
    protected List<Lbxx> getTzgg(DBMUtil dbmUtil, String id, String sql) throws Exception {
        if (StringUtil.isBlank(sql)) {
            sql = "select t.id,t.title,to_char(t.pubtime,'yyyy-MM-dd HH24:mi:ss') as time,0 as isnew" +
                    " from (select * from tblog a order by a.pubtime desc,id desc) t where t.category in ('" + id.replaceAll(",", "','") + "') and rownum <=100";
        }
        return dbmUtil.queryAllBeanList(sql, Lbxx.class);
    }

    /**
     * 获取待办事项
     *
     * @param userloginid 用户登录账号
     * @return ---
     * @throws Exception
     */
    protected List<Lbxx> getWorkflowForIFrame(String userloginid) throws Exception {
        List<Lbxx> list = new ArrayList<Lbxx>();
        List<TLbxx> lbxxList = DBUtil.queryAllBeanList("select a.*,t.link as link from t_lbxx a left join t_db t on t.code=a.db" +
                " where a.upid='1' and a.state='1' order by a.orderno", TLbxx.class);
        String casUrl = ConfigUtil.getString("cas.server.url").replaceAll("/", "%2F").replace(":", "%3A");
        for (TLbxx lbxx : lbxxList) {
            try {
                String url = lbxx.getLink().replaceAll(":", "%253A").replaceAll("/", "%252F");
                list.addAll(getTzgg(new DBMUtil(lbxx.getDb()), null, " select cur.entry_id as id,'" +
                        casUrl + "%2Flogin%3Fservice%3D" + url + "%252FUIProcessor%253F" +
                        "Creator%253Dworkflow%2526Table%253D'||wf.name||'%2526WorkID%253D'||cur.entry_id||'%2526StepID%253D'" +
                        "||cur.step_id||'%2526PageOnly%253Dtrue' as depart," +
                        "case when wf.subject is null then aa.wf_describe else wf.subject end as title,wf.init_date as time" +
                        " from os_wfentry wf left join os_currentstep cur on wf.id=cur.entry_id" +
                        " left join tuser t on instr(','||cur.owner||',',','||t.id||',')>0" +
                        " left join tuser init_t on wf.initiator=init_t.id left join os_workflowdefs aa on aa.wf_name=wf.name" +
                        " where t.userid= '" + userloginid + "' order by cur.start_date desc"));
            } catch (Exception e) {
                error("{} getWorkflow error : {}", lbxx.getDb(), e);
                continue;
            }
        }

        Collections.sort(list, new Comparator<Lbxx>() {
            @Override
            public int compare(Lbxx o1, Lbxx o2) {
                if (o2.getTime().getTime() - o1.getTime().getTime() >= 0) {
                    return 1;
                } else {
                    return -1;
                }
            }
        });
        return list;
    }

    /**
     * 获取待办事项
     *
     * @param userloginid 用户登录账号
     * @return ---
     * @throws Exception
     */
    protected List<Lbxx> getWorkflowNoFrame(String userloginid) throws Exception {
        List<Lbxx> list = new ArrayList<Lbxx>();
        List<TLbxx> lbxxList = DBUtil.queryAllBeanList("select a.*,t.link as link from t_lbxx a left join t_db t on t.code=a.db" +
                " where a.upid='1' and a.state='1' order by a.orderno", TLbxx.class);
        String casUrl = ConfigUtil.getString("cas.server.url");
        for (TLbxx lbxx : lbxxList) {
            try {
                String url = lbxx.getLink().replaceAll(":", "%3A").replaceAll("/", "%2F");
                list.addAll(getTzgg(new DBMUtil(lbxx.getDb()), null, " select cur.entry_id as id,'" +
                        casUrl + "/login?service=" + url + "%2FUIProcessor%3F" +
                        "Creator%3Dworkflow%26Table%3D'||wf.name||'%26WorkID%3D'||cur.entry_id||'%26StepID%3D'" +
                        "||cur.step_id||'%26PageOnly%3Dtrue' as depart," +
                        "case when wf.subject is null then aa.wf_describe else wf.subject end as title,wf.init_date as time" +
                        " from os_wfentry wf left join os_currentstep cur on wf.id=cur.entry_id" +
                        " left join tuser t on instr(','||cur.owner||',',','||t.id||',')>0" +
                        " left join tuser init_t on wf.initiator=init_t.id left join os_workflowdefs aa on aa.wf_name=wf.name" +
                        " where t.userid= '" + userloginid + "' order by cur.start_date desc"));
            } catch (Exception e) {
                error("{} getWorkflow error : {}", lbxx.getDb(), e);
                continue;
            }
        }

        Collections.sort(list, new Comparator<Lbxx>() {
            @Override
            public int compare(Lbxx o1, Lbxx o2) {
                if (o2.getTime().getTime() - o1.getTime().getTime() >= 0) {
                    return 1;
                } else {
                    return -1;
                }
            }
        });
        return list;
    }

    /**
     * 设置消息提醒模块中的周次 日期等
     *
     * @param request --
     */
    protected void initDate(HttpServletRequest request) {
        String[] weeks = new String[]{"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
        Calendar cal = Calendar.getInstance();
        String week = weeks[cal.get(Calendar.DAY_OF_WEEK) - 1];
        request.setAttribute("weekday", week); //周几
        request.setAttribute("year", cal.get(Calendar.YEAR));
        request.setAttribute("month", cal.get(Calendar.MONTH) + 1);
        request.setAttribute("date", cal.get(Calendar.DAY_OF_MONTH));
    }

    /**
     * 查询未读消息
     *
     * @param request
     */
    protected List<TMessage> getMessage(HttpServletRequest request, TSysUser user, String zt, String db, int rownum) {
        String selsql = "  select * from t_message where zt=? and userid=? and ly=?";
        Pager pager = new Pager();
        pager.setEachPageRows(rownum);
        long c = DBUtil.count("select count(*) from (" + selsql + ")", zt, user.getUserloginid(), db);
        pager.setTotalRows(c);
        List<TMessage> list = DBUtil.queryPageBeanList(pager, selsql, TMessage.class, zt, user.getUserloginid(), db);
        return list;
    }
}
